
import queue
import sys
import _thread
import time
import random
import os

from typing import MappingView
from PyQt5 import QtCore, QtGui, QtWidgets

from controller.counter import CounterMainWindow

from libs.keyboard import Keyboard
from libs.counter import ImageCounter
from libs.qrcode import Qrcode
from libs.ioctrl import IoCtrl

from bases import globalvar
from bases.player import SoundPlayer


# 延时线程， 所有的延时任务都放到这里，比如LED延时关闭
def delay(threadName):
    while True:
        #以10ms作为间隔
        time.sleep(0.1)
        IoCtrl.delay()


# 扫描键盘
def scan(threadName, queue: queue.Queue):
    kb = Keyboard()
    while True:
        time.sleep(0.01)
        kb.scan(q)

#分发任务
def pullKeyEvent(threadName, queue: queue.Queue):
    while True:
        time.sleep(0.1)
        key = queue.get()
        print(key)
        
        if (key =='0'):
            brs = Qrcode.detect()
            if(brs is not None):
                mainWindow.changeInfomation(brs[0])
        if (key=='Counter' or key == 'lightOpen') :
            count = ImageCounter.capAndAnalysis()
            mainWindow.changeNumber(count)
            SoundPlayer.play(count)
        if (key =='PowerKey-Long'):
            cmd="sudo shutdown -h now"
            os.system(cmd)
        if (key =='8-Long'):
            mainWindow.close()
       

if __name__== '__main__':
    app = QtWidgets.QApplication(sys.argv)

    mainWindow = CounterMainWindow()
    mainWindow.showFullScreen()
    #mainWindow.showMaximized()
    
    #https://www.cnblogs.com/yuanjunyan/p/15044381.html
    # 各种初始化
    Keyboard.gpioinit()
    globalvar._init()
    SoundPlayer.init()

    q = queue.Queue(maxsize=1)

    # 创建两个线程
    try:
        _thread.start_new_thread(scan, ("Thread-keyboardScanner", q))
        _thread.start_new_thread(delay, ("Thread-delay", ))
        _thread.start_new_thread(pullKeyEvent, ("Thread-1", q))
    except:
        print("Error: 无法启动线程")
    
    sys.exit(app.exec_())